package de.tto.dating.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.tto.dating.entities.User;
import de.tto.dating.entities.UserDAO;
import de.tto.dating.utils.EmailService;

public class ConfirmServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 818634436352709990L;

	// private static final Logger log = Logger.getLogger(RegisterServlet.class
	// // .getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String oid = req.getParameter("user");
		String key = req.getParameter("key");

		if (oid == null || oid.isEmpty() || key == null || key.isEmpty()
				|| key.length() > 20) {

			resp.sendError(404);
			return;
		}

		Long userOid = null;

		try {
			userOid = Long.parseLong(oid);
		} catch (Exception e) {
			resp.sendError(404);
			return;
		}

		UserDAO userDAO = new UserDAO();
		User foundUser = userDAO.ofy().find(User.class, userOid);

		if (foundUser == null) {
			req.setAttribute("msg", "account.confirm.userNotFound");
			getServletContext().getRequestDispatcher("/error.jsp").forward(req,
					resp);	
			return;
		}

		if (foundUser.isConfirmed()){
			resp.sendRedirect("/login.jsp");
			return;
		}
		
		if (foundUser.getConfirmKey().equals(key)) {
			foundUser.setConfirmed(true);
			userDAO.save(foundUser);
			new EmailService().sendWelcomeEmail(foundUser, getServletContext());
			req.setAttribute("msg", "account.successful.confirmed");
			getServletContext().getRequestDispatcher("/login.jsp").forward(req,
					resp);
			return;
		}

		req.setAttribute("msg", "account.confirm.wrong.key");
		getServletContext().getRequestDispatcher("/error.jsp").forward(req,
				resp);	

	}

}
